package com.seari.tunnel.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.seari.tunnel.entity.RecordAudit;
import com.seari.tunnel.entity.SettlementHistory;
import com.seari.tunnel.service.IDynamicService;
import com.seari.tunnel.service.ISubsidenceMonitorService;

@Controller
public class SecurityProtectionController {
	private final String CJJC_PAGE = "/cjjc";
	private final String CJJC2_PAGE = "/cjjc2";
	private final String DTHP_PAGE = "/dthp";
	private final String BASH_PAGE = "/bash";
	private final String JLCX_PAGE = "/jlcx";
	
	private final String SAVE_PATH = "C:/save/";
	
	@Autowired
	ISubsidenceMonitorService subsidenceMonitorService;
	@Autowired
	IDynamicService dynamicService;
	
	@RequestMapping(value="/cjjc")
	public ModelAndView cjjc(){
		
		return new ModelAndView(CJJC_PAGE);
	}
	
	@RequestMapping(value="/cjjc2")
	public ModelAndView cjjc2(){
		
		return new ModelAndView(CJJC2_PAGE);
	}
	
	@RequestMapping(value="/dthp")
	public ModelAndView dthp(){
		
		return new ModelAndView(DTHP_PAGE);
	}
	
	@RequestMapping(value="/bash")
	public ModelAndView bash(){
		
		return new ModelAndView(BASH_PAGE);
	}
	
	@RequestMapping(value="/jlcx")
	public ModelAndView jlcx(){
		
		return new ModelAndView(JLCX_PAGE);
	}
	
	@RequestMapping(value = "/findSettlement")
	@ResponseBody
	public Object getSettlement(@RequestParam("date") String date) {
		List<SettlementHistory> data = subsidenceMonitorService.findSettlement(date);
		return data;
	}
	
	@RequestMapping(value = "/findPointInfo")
	@ResponseBody
	public Object getPointInfo(@RequestParam("point") String point,@RequestParam("date") String date) {
		List<SettlementHistory> data = subsidenceMonitorService.findPointInfo(point,date);
		return data;
	}
	
	@RequestMapping(value = "/loadRecordAuditGrid")
	@ResponseBody
	public Object getRecordAuditGrid() {
		List<RecordAudit> data = dynamicService.findRecordAudits();
		return data;
	}
	
	@RequestMapping(value="/addRecordAudit")
	public ModelAndView addRecordAudit(@RequestParam("bname") String bname,@RequestParam("uname") String uname,@RequestParam("recordFile") MultipartFile recordFile,HttpServletRequest req){
		
		String savePath =  SAVE_PATH+"recordAudit";
        File file = new File(savePath);
        if (!file.exists() && !file.isDirectory()) {
            //创建目录
            file.mkdir();
       }
        String fileType = recordFile.getContentType();
        String filename = recordFile.getOriginalFilename();
           RecordAudit recordAudit = new RecordAudit();
           recordAudit.setCompany(bname);
           recordAudit.setContactUnit(uname);
           recordAudit.setCreateTime(new Timestamp(new Date().getTime()));
           recordAudit.setUploader("admin");
        if("application/vnd.openxmlformats-officedocument.wordprocessingml.document".equals(fileType) || "application/msword".equals(fileType) || "application/pdf".equals(fileType) || "image/jpeg".equals(fileType)){
        	filename = filename.substring(filename.lastIndexOf("\\")+1);
        	try {
				InputStream in = recordFile.getInputStream();
				FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);
				//创建一个缓冲区
			    byte buffer[] = new byte[1024];
			    //判断输入流中的数据是否已经读完的标识
				int len = 0;
				 while((len=in.read(buffer))>0){
					//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
					out.write(buffer, 0, len);
					 }
					//关闭输入流
					in.close();
					//关闭输出流
					out.close();
			} catch (IOException e) {
				
				e.printStackTrace();
			}
        	recordAudit.setRecord(filename);
 		    dynamicService.addRecordAudit(recordAudit);
		   
 		}
        return new ModelAndView(JLCX_PAGE);
	}
	
	@RequestMapping(value="/recordAuditDownload")
	public void recordAuditDownload(HttpServletRequest req, HttpServletResponse res){
		InputStream is = null;
		OutputStream os = null;
		try {
			res.reset();
			String fileName = "新建工程项目管理备案审核表.pdf";
			 if(req.getHeader("User-Agent").toLowerCase().indexOf("firefox")>0){
	                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
	            }else if (req.getHeader("User-Agent").toUpperCase().indexOf("MSIE")>0){
	                fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
	            }else{
	                fileName = URLEncoder.encode(fileName, "UTF-8");
	            }
		res.setCharacterEncoding("utf-8");
		res.setContentType("application/pdf");
		res.setHeader("Content-Disposition", "attachment;fileName=\"" + fileName + "\"");

            String path = Thread.currentThread().getContextClassLoader()
                    .getResource("").getPath()
                    + "download";//这个tunneled目录为啥建立在classes下的
            is = new FileInputStream(new File(path
                    + File.separator + "新建工程项目管理备案审核表.pdf"));
 
            os = res.getOutputStream();
            byte[] mybyte = new byte[8192];
            int len = 0;
            while ((len = is.read(mybyte)) != -1) {
                os.write(mybyte, 0, len);
            }

            os.flush();
             // 这里主要关闭。
            os.close();
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	
	@RequestMapping(value="/recordAuditGridDownload")
	public void recordAuditGridDownload(@RequestParam("file") String file,HttpServletRequest req, HttpServletResponse res){
		InputStream is = null;
		OutputStream os = null;
		try {
			res.reset();
			String fileName = new String(file.getBytes("ISO8859-1"),"UTF-8");
			String fName = "";
			if(req.getHeader("User-Agent").toLowerCase().indexOf("firefox")>0){
				fName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
            }else if (req.getHeader("User-Agent").toUpperCase().indexOf("MSIE")>0){
            	fName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
            }else{
            	fName = URLEncoder.encode(fileName, "UTF-8");
            }
			res.setCharacterEncoding("utf-8");
			
			if(fileName.contains("doc") || fileName.contains("docx")){
				res.setContentType("application/msword");
			}
            if(fileName.contains("pdf")){
            	res.setContentType("application/pdf");
			}
            if(fileName.contains("jpg")){
            	res.setContentType("image/jpeg");
            }
		
		res.setHeader("Content-Disposition", "attachment;fileName=\"" + fName + "\"");

            String path = SAVE_PATH+"recordAudit";
            File filePath = new File(path);
            is = new FileInputStream(new File(filePath
                    + File.separator + fileName));
 
            os = res.getOutputStream();
            byte[] mybyte = new byte[8192];
            int len = 0;
            while ((len = is.read(mybyte)) != -1) {
                os.write(mybyte, 0, len);
            }

            os.flush();
             // 这里主要关闭。
            os.close();
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
}
